package com.data.dev.utils;

import com.data.dev.common.exception.AlarmException;
import com.data.dev.common.exception.ConfErrorCode;
import com.data.dev.common.javabean.BaseBean;
import com.data.dev.key.ConfigurationKey;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.junit.Test;

import java.io.IOException;
@Slf4j
public class HttpUtils extends BaseBean {

    public static String ALARM_MSG_BASE = "&msg=";

    /**
     * 推送企业微信告警的URL
     */
    public static String PUSH_ALARM_BY_WECHAT_FOR_BLACKLIST_DNS_URL = "https://soc.wangxiaoming.com/api/sendMsg_to_wx/?user=";


    /**
     * 查询IP的归属用户
     */
    public static String QUERY_IP_BELONG_USER_URL = "https://soc.wangxiaoming.com/api/query_ip2user/";


    /**
     * @param dnsTopicClientIP : 由Kafka的DNS Topic中解析出来的client_ip
     * @return boolean
     */
    public static String  getUserByClientIp(String dnsTopicClientIP) {

        String  userBelongIp = "";

        Connection connect = Jsoup.connect(QUERY_IP_BELONG_USER_URL + dnsTopicClientIP);
        Connection.Response ipCheckResp;
        if("".equals(dnsTopicClientIP) || null == dnsTopicClientIP || !IPUtils.isIpAddr(dnsTopicClientIP)) return  "None";
        try {
            ipCheckResp = connect.ignoreContentType(Boolean.TRUE).ignoreHttpErrors(Boolean.TRUE).method(Connection.Method.GET).execute();
        } catch (IOException e) {

           log.info("报错信息：{}" + e.getMessage());
            throw AlarmException.asAlarmException(ConfErrorCode.HTTP_CHECK_ERROR, e);
        }

        if( ipCheckResp.statusCode() == ConfigurationKey.KAFKA_DNS_BLACKLIST_IP_CHECK_STATUS_CODE){
            userBelongIp = ipCheckResp.body();
        }

        return userBelongIp;
    }


    /**
     * 2022年6月17日15:32:59
     * 推送告警消息到企业微信
     * @param user：ip归属用户
     * @param msg：告警消息体
     * @return boolean:是否推送成功
     */
    public static boolean pushAlarmMsgToWechatWork(String user,String msg) {

        String pushBlacklistDnsByWechatWorkUrl = PUSH_ALARM_BY_WECHAT_FOR_BLACKLIST_DNS_URL + user + ALARM_MSG_BASE + msg;
        boolean isPushToWechatAboutThisBlackListDns;


        Connection connect = Jsoup.connect(pushBlacklistDnsByWechatWorkUrl);
        Connection.Response pushToWechatResp;
        try {
            pushToWechatResp = connect.ignoreContentType(Boolean.TRUE).ignoreHttpErrors(Boolean.TRUE).method(Connection.Method.POST).execute();
        } catch (IOException e) {

            throw AlarmException.asAlarmException(ConfErrorCode.HTTP_PUSH_ERROR, e);
        }

        isPushToWechatAboutThisBlackListDns = pushToWechatResp.statusCode() == ConfigurationKey.KAFKA_DNS_BLACKLIST_IP_CHECK_STATUS_CODE;
        return isPushToWechatAboutThisBlackListDns;

    }

}


